package com.aote.rs;

import java.util.Hashtable;

import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

import com.browsesoft.resource.BasicResource;
import com.browsesoft.resource.ResourceTool;
import net.sf.json.JSON;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.browsesoft.Entity;
import com.browsesoft.EntityManager;
import com.browsesoft.ManagerGroup;
import com.browsesoft.SequenceFind;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.resource.LicensePolicyEntity;
import com.browsesoft.resource.Resource;
import org.springframework.stereotype.Component;

@Path("license")
@Component
public class LicenseService {
	static Logger log = Logger.getLogger(LicenseService.class);
	
	/**
	 * 授权资源
	 */
	private Resource resource;

	/**
	 * 被授权资源
	 */
	private Resource byResource;
//	private SessionFactory sessionFactory;

    /**
     * 保存授权策略
     * @param str: {parentid: 授权资源, licenses: [{授权策略}]}
     * @return
     * @throws Exception
     */
	@POST
	@Path("save")
	public String saveOrModify(String str) throws Exception {
		log.debug("策略授权-save++:"+str);
        JSONObject obj = new JSONObject(str);
        if(obj.has("data")){
        	JSONObject data = obj.getJSONObject("data");
    		String id;
    		String selfid;
    		// 设置对象号
    		try {
    			// 设置对象号
    			id = Integer.toString(SequenceFind.getID());
    			// 设置多版本时，不同版本，同一个对象的唯一标识
    			selfid = SequenceFind.getID() + "";
    		} catch (Exception e) {
    			throw new RuntimeException(e);
    		}
    		System.out.println("生成的id："+id);
    		System.out.println("生成的selfid："+selfid);
        	LicensePolicyEntity lp = new LicensePolicyEntity();
    		lp.setTableName("t_licensepolicy");
    		lp.setEntityType("licensepolicy");
    		lp.getAttributes().put("tablename", "t_licensepolicy");
    		lp.getAttributes().put("entitytype", "licensepolicy");
    		lp.getAttributes().put("parentid", data.get("parentid").toString());
    		lp.getAttributes().put("resourceid", data.get("resourceid").toString());
    		this.resource = (Resource) EntityManager.getInstance().getObject(data.get("resourceid").toString());
    		lp.setResource(resource);
    		lp.getAttributes().put("byresourceid", data.get("byresourceid").toString());
    		this.byResource = (Resource) EntityManager.getInstance().getObject(data.get("byresourceid").toString());
    		lp.setByResource(byResource);
    		lp.getAttributes().put("isinherit", data.get("isinherit").toString());
    		lp.getAttributes().put("byisinherit", data.get("byisinherit").toString());
    		lp.getAttributes().put("resourceresult", data.get("resourceresult").toString());
    		lp.getAttributes().put("byresourceresult", data.get("byresourceresult").toString());
    		lp.getAttributes().put("righttype", data.get("righttype").toString());
    		lp.getAttributes().put("licensepolicy", "");
    		lp.insert();
    		return "";
        }else{
        	 // 删除原有的授权策略
            String parentId = obj.getString("parentid");
            this.delete(parentId);

            // 对每一项授权策略，重新添加
            JSONArray array = obj.getJSONArray("licenses");
    		// 给授权资源设置是否有授权信息标识
    		boolean hasLicense = (array.length() == 0 ? false : true);
    		Resource res = (Resource)EntityManager.getInstance().getObject(parentId);
    		res.getAttributes().put("haslicense", hasLicense);
    		res.update();

            for (Object o : array) {
                JSONObject data = (JSONObject)o;
                String id;
                String selfid;
                // 设置对象号
                try {
                    // 设置对象号
                    id = Integer.toString(SequenceFind.getID());
                    // 设置多版本时，不同版本，同一个对象的唯一标识
                    selfid = SequenceFind.getID() + "";
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生成的id：" + id);
                System.out.println("生成的selfid：" + selfid);
                LicensePolicyEntity lp = new LicensePolicyEntity();
                lp.setTableName("t_licensepolicy");
                lp.setEntityType("licensepolicy");
                lp.getAttributes().put("tablename", "t_licensepolicy");
                lp.getAttributes().put("entitytype", "licensepolicy");
                lp.getAttributes().put("parentid", data.get("parentid").toString());
                lp.getAttributes().put("resourceid", data.get("resourceid").toString());
                this.resource = (Resource) EntityManager.getInstance().getObject(data.get("resourceid").toString());
                lp.setResource(resource);
                lp.getAttributes().put("byresourceid", data.get("byresourceid").toString());
                this.byResource = (Resource) EntityManager.getInstance().getObject(data.get("byresourceid").toString());
                lp.setByResource(byResource);
                lp.getAttributes().put("isinherit", data.get("isinherit").toString());
                lp.getAttributes().put("byisinherit", data.get("byisinherit").toString());
                lp.getAttributes().put("resourceresult", data.get("resourceresult").toString());
                lp.getAttributes().put("byresourceresult", data.get("byresourceresult").toString());
                lp.getAttributes().put("righttype", data.get("righttype").toString());
                lp.getAttributes().put("licensepolicy", "");
                // 添加新的授权策略
                lp.insert();
            }
    		return "";
        }
       
	}

    /**
     * 删除授权策略
     * @param parentId
     * @throws Exception
     */
	@DELETE
	@Path("{parentid}")
	public void delete(@PathParam("parentid") String parentId) throws Exception {
		// 根据parentid获取所有策略
		String[][] data = getData(parentId);
		for (int i = 1; i < data.length; i++) {
			Hashtable ht = DBTools.getAttributes(data, i);
			String id = (String)ht.get("id");
			this.deleteLicense(id);
		}
	}

    /**
     * 获得授权策略数据
     * @param str
     * @return
     * @throws Exception
     */
    @POST
    @Path("getData")
    public String getIds(String str) throws Exception {
        JSONObject obj = new JSONObject(str);
        System.out.println(obj.getString("parentid"));
        String[][] data = getData(obj.getString("parentid"));
        String ids = "";
        if (data.length < 2) {
            return "";
        }
        // 把查询到的内容转换成JSON串
        JSONArray array = new JSONArray();
        for (int i = 1; i < data.length; i++) {
            JSONObject json = new JSONObject();
            for(int j = 0; j < data[0].length; j++) {
                json.put(data[0][j], data[i][j]);
            }
            // 取得被授权资源全名称路径
            String names = this.getByResourceNames(json);
            json.put("names", names);
            array.put(json);
        }
        String result = array.toString();
        log.debug(result);
        return result;
    }

    /**
     * 获得授权资源对被授权资源有权限的原因
     * @param resourceid 授权资源
     * @param byresourceid 被授权资源
     * @return 授权策略列表
     */
    public String getLicenses(String resourceid, String byresourceid) {
        return null;
    }

    /**
	 * 根据id删除对应管理器资源和数据库数据
	 * @param id
	 * @throws Exception
	 */
	public void deleteLicense(String id) throws Exception {
		Object obj = ManagerGroup.getManagerGroup().getObject(id);
		((Entity)obj).delete();
	}
	
	public String[][] getData(String parentid) throws Exception {
		String sql = "select *  from t_licensepolicy where parentid='"+parentid+"'";
		System.out.println(sql);
		String[][] data = DBTools.executeQueryWithTableHead(sql);
		return data;
	}
	
	/**
	 * 获取被授权资源的中文路径全名
	 * @param json
	 * @return
	 */
	private String getByResourceNames(JSONObject json) {
		String id = json.getString("byresourceid");
		BasicResource res = (BasicResource)EntityManager.getInstance().getObject(id);
		String names = ResourceTool.getFullPathName(res, "name", 0);
		return names;
	}
}
